﻿using System;
using System.Collections.Concurrent;

using RayDen.Library.Components.SystemComponents;
using RayDen.Library.Core.Components;

namespace RayDen.RayEngine.Corrector.Managers
{
    public class EngineCommand
    {
        public int Id;
        public string Name, Args, Comment;
        public DateTime StartDate;
        public TimeSpan ExecutionTime;

        public Object Param;
    }

    public class EngineCommandContext
    {
        public bool? Success;
        public bool? AddToQueue;
        public string Message;
    }


    public class CommandManager : Singleton<CommandManager>
    {
        protected ConcurrentQueue<EngineCommand> commandQueue;

        public event Func<EngineCommand, EngineCommandContext> OnAddCommand;
        public event Func<EngineCommand, EngineCommandContext> OnExecuteCommand;



        public CommandManager()
        {
            commandQueue = new ConcurrentQueue<EngineCommand>();
        }

        public void Add(EngineCommand command)
        {
            if (this.OnAddCommand != null)
            {
                var context = this.OnAddCommand(command);
                if (!context.Success.GetValueOrDefault())
                {
                    Tracer.TraceLine("CommandManager - Couldn't add command to queue : ", context.Message);
                    return;
                }
                if (!context.AddToQueue.GetValueOrDefault())
                    return;
            }
            commandQueue.Enqueue(command);
        }

        public EngineCommand Pop()
        {
            EngineCommand command;
            if (commandQueue.TryDequeue(out command))
            {
                if (this.OnExecuteCommand != null)
                {
                    var ctx = this.OnExecuteCommand(command);
                    return command;
                }
            }
            return null;
        }

    }
}
